<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- 头部左侧 -->
        <div class="media-display">
          <el-link :underline="false" style="font-size: 20px">订单列表</el-link>
          <el-divider direction="vertical"></el-divider>
          <el-link :underline="false" style="font-size: 20px">要查询的订单：</el-link>
          <el-button :type="condition.orderSate.unpaid ? 'primary' : 'info'" plain @click="choice($event.target,0)">未支付</el-button>
          <el-button :type="condition.orderSate.paid ? 'success' : 'info'" plain @click="choice($event.target,1)">已支付</el-button>
          <el-button :type="condition.orderSate.cancel ? 'danger' : 'info'" plain @click="choice($event.target,2)">已取消</el-button>
        </div>
        <!-- 头部右侧 -->
        <div style="margin-left: auto">
          <el-form :inline="true" :model="condition" class="demo-form-inline">
            <el-form-item label="用户ID">
              <el-input v-model="condition.userId" placeholder="用户ID模糊查询"></el-input>
            </el-form-item>

            <el-form-item label="订单ID">
            <el-input v-model="condition.orderId" placeholder="订单ID精确查询"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="success" plain @click="init">查询</el-button>
              <el-button style="margin-left: 10px" type="primary" plain @click="viewAll">全部订单</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 内容 -->
      <div class="text">
        <el-table
          v-loading="listLoading"
          highlight-current-row
          :data="tableData.list"
          style="width: 100%">
          <!-- 展开行 -->
          <el-table-column type="expand">
            <template slot-scope="props">
              <el-table
                :data="props.row.historyCartVoList"
                style="width: 100%">
                <el-table-column
                  prop="date"
                  label="产品图片">
                  <template slot-scope="scope">
                    <img @click="$router.push(`/product/${scope.row.productId}`)"
                         style="cursor: pointer"
                         :src="prefix + scope.row.specsImg" width="80" height="80" alt="商品图片">
                  </template>
                </el-table-column>
                <el-table-column
                  prop="name"
                  label="产品名称">
                </el-table-column>
                <el-table-column
                  prop="address"
                  label="规格">
                  <template slot-scope="scope">
                    {{ scope.row.productSpecs | parseSpecs }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="price"
                  label="价格">
                </el-table-column>
                <el-table-column
                  prop="total"
                  label="数量">
                </el-table-column>
              </el-table>

            </template>
          </el-table-column>
          <el-table-column
            type="index"
            :index="(this.tableData.currentPage-1)*this.tableData.pageSize + 1"
            width="50">
          </el-table-column>
          <el-table-column
            prop="orderId"
            label="订单号">
          </el-table-column>
          <el-table-column
            prop="userId"
            label="用户id">
          </el-table-column>
          <el-table-column
            prop="totalAmount"
            label="总金额"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | timestampToTime}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="支付时间"
            prop="createTime">
            <template slot-scope="scope">
              <span>{{ scope.row.updateTime | timestampToTime}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="状态">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper" >
                <el-tag style="cursor: pointer;width: 60px;text-align: center"
                        :type="scope.row.orderState === 0 ? 'primary': (scope.row.orderState === 1 ? 'success' : 'danger')">
                  <span>{{ scope.row.orderState | orderFilter}}</span>
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button  size="small" type="primary" @click="toOrderDetail(scope.row.orderId)">查看详情</el-button>
            </template>

          </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination style="text-align: center"
                       @current-change="handleCurrentChange"
                       :current-page="this.tableData.currentPage"
                       :page-size="this.tableData.pageSize"
                       layout="total, prev, pager, next, jumper"
                       :total="this.tableData.total">
        </el-pagination>
      </div>
    </el-card>

  </div>
</template>


<script>
  import { getAllHistoryOrderInfoReq } from "@/api/order";
  import settings from '@/settings'

  export default {
    name: "Order",
    data(){
      return{
        prefix : settings.prefix || '/product-mainImg/phone/xiaomi/k50.jpg',// 全局前缀
        listLoading: true,// 表格loading
        tableData : {},// 历史订单信息

        condition: {// 搜索条件
          orderSate: {// 存放要搜索的订单状态类型
            unpaid: true,
            paid: true,
            cancel: true,
          },
          userId : '',// 用户id
          orderId : '',// 订单id
          currentPage: 1,// 当前页默认为1
        },
      }
    },
    methods : {
      toOrderDetail(orderId){
        this.$router.push(`/order/orderDetail/${orderId}`)
      },
      init(){
        if (!Object.values(this.condition.orderSate).includes(true)){
          this.$message.warning({message: '至少选择一个状态'})
          return;
        }else if (/[^0-9.]/g.test(this.condition.orderId)){
          this.$message.warning({message: '订单id只能输入数字'})
          return;
        }
        if (this.condition.orderId !== ''){
          Object.assign(this.$data.condition.orderSate, this.$options.data().condition.orderSate);

        }
        this.listLoading = true
        getAllHistoryOrderInfoReq({ condition : this.condition }).then(response => {
          console.log(response)
          if (response.state === true) {
            this.tableData = response.data.page//
            this.listLoading = false
            this.$notify.success({title: '成功',message: response.message, duration: 1500});
          }else{
            this.$notify.warning({title: '失败',message: response.message, duration: 1500});
          }
        })
      },
      handleCurrentChange(currentPage){//处理分页数据
        this.condition.currentPage = currentPage;
        this.init()
      },
      viewAll(){//查看全部用户
        Object.assign(this.$data.condition, this.$options.data().condition);
        this.init();
      },
      handleState(){
        console.log(this.condition)
      },
      choice(event, categoryId){
        switch (categoryId) {
          case 0 : this.condition.orderSate.unpaid = !this.condition.orderSate.unpaid;break;
          case 1 : this.condition.orderSate.paid = !this.condition.orderSate.paid;break
          case 2 : this.condition.orderSate.cancel = !this.condition.orderSate.cancel;break
        }
        if(event.nodeName === 'SPAN' || event.nodeName === 'I'){
          event = event.parentNode;
        }
        event.blur();
      },
      gotoDetail(productId){// 去商品详情页
        this.$router.push(`/product/detail/${productId}`)
      },
      updateState(index ,id){
        console.log(index,id)
      },

      handleClose(done) {
        this.$confirm('确认关闭？').then(_ => {done();}).catch(_ => {});
      },
    },
    filters: {
      orderFilter(orderState){
        switch (orderState) {
          case 0 : return "未支付";
          case 1 : return "已支付";
          case 2 : return "已取消";
        }
      },
      // 时间戳转换成时间
      timestampToTime (timestamp) {
        let date = new Date(timestamp) //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
        let D = date.getDate() + ' '
        let h = date.getHours() + ':'
        let m = date.getMinutes() + ':'
        let s = date.getSeconds()
        s = s < 10 ? '0' + s : s;
        return Y+M+D+h+m+s;
      },
      parseSpecs(specs){
        let specsObj = JSON.parse(specs);
        let str = "";
        Object.keys(specsObj).forEach((key)=>{
          //console.log(specsObj[key])
          str += specsObj[key] + " "
        })
        return str
      }
    },
    beforeMount (){//初始化数据
      this.init();
    },
    mounted(){
    },
  }
</script>

<style scoped>

  @media (max-width: 1100px){
    .media-display{
      display: none;
    }
  }

  .el-card__header{
    background-color: rgba(0,0,0,.03);
  }
  .el-card__body{
    padding-top: 0;
  }
  .clearfix{
    display: flex;
    align-items: center;
  }
  .text {
    font-size: 14px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .demo-table-expand {
    font-size: 0;
  }
  >>> .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  /*头部*/
  .el-form{
    width: auto;
  }
  .el-form-item{
    margin-bottom: 0;
  }

</style>
